package cacco.jp.mld.panel.dao;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import cacco.jp.mld.panel.entity.UrlEntity;

@Repository
public class UrlDao {

	private static int totalRecords;

	@Autowired
	private SessionFactory sessionFactory;

	@Transactional
	public int add(UrlEntity url) {
		int id = url.getId();
		this.sessionFactory.getCurrentSession().save(url);
		id = url.getId();
		return id;
	}

	@Transactional
	public List<UrlEntity> getAll() {
		return this.sessionFactory.getCurrentSession()
				.createQuery("from UrlEntity").list();
	}

	@Transactional
	public void delete(Integer id) {
		UrlEntity employee = (UrlEntity) sessionFactory.getCurrentSession()
				.load(UrlEntity.class, id);
		if (null != employee) {
			this.sessionFactory.getCurrentSession().delete(employee);
		}
	}

	@Transactional
	public UrlEntity findById(int id) {
		Query query = sessionFactory.getCurrentSession().getNamedQuery(
				"findUrlById");
		query.setInteger("id", id);
		UrlEntity loginObj = (UrlEntity) query.uniqueResult();
		return loginObj;
	}

	@Transactional
	public void update(UrlEntity url) {
		sessionFactory.getCurrentSession().update(url);
	}

	@Transactional
	public List<UrlEntity> getAlByPage(int pageSize, int page, String sidx,
			String sord) {
		List<UrlEntity> list = null;
		Query query = sessionFactory.getCurrentSession().createQuery(
				"from UrlEntity order by " + sidx + " " + sord);
		totalRecords = query.list().size();
		query.setFirstResult((page - 1) * pageSize);
		query.setMaxResults(pageSize);
		list = (List<UrlEntity>) query.list();
		return list;
	}

	public static int getTotalRecords() {
		return totalRecords;
	}
}